package nl.foldervisualizer.controller
{
	import flash.filesystem.File;
	
	import nl.foldervisualizer.business.FolderVisualizer;
	import nl.foldervisualizer.events.UIEvent;
	import nl.foldervisualizer.events.UIEventKind;
	import nl.foldervisualizer.model.Model;
	
	public class NavigationController extends MultiActionController
	{
		private var _visualizer:nl.foldervisualizer.business.FolderVisualizer
		private var _model:Model;
	
		public function set model(model:Model):void {
			_model = model
		}
		
		public function set visualizer(visualizer:nl.foldervisualizer.business.FolderVisualizer):void {
			_visualizer = visualizer
		}
		
		public function NavigationController()
		{
			super();
			super._handlerMappings.put(UIEventKind.BACK, this.handleBack)
			super._handlerMappings.put(UIEventKind.DIRECT_LINK, this.handleDirect)
			super._handlerMappings.put(UIEventKind.DENSITY_CHANGE, this.handleDensityChanged)
			super._handlerMappings.put(UIEventKind.DRILLDOWN, this.handleDrilldown)
		}
		
		private function handleBack(event:UIEvent):void {
			if ((_model.breadCrumps.length - 1) >= 0) {
				var file:File = _model.breadCrumps.removeItemAt(_model.breadCrumps.length - 1) as File
				if (file != null) {
					_model.folderToVisualize = file
					_model.folderData = _visualizer.visualize(_model.folderToVisualize, _model.limit)
					_model.selectedItem = null
				}
			}
		}
		
		private function handleDirect(event:UIEvent):void {
			var file:File = event.payload as File
			_model.folderToVisualize = file
			var index:int = _model.breadCrumps.getItemIndex(file)
			var lastIndex:int = _model.breadCrumps.length - 1
			for (var i:int = lastIndex; i >= index; i--) {
				_model.breadCrumps.removeItemAt(i)
			}
			_model.folderData = _visualizer.visualize(_model.folderToVisualize, _model.limit)
			_model.selectedItem = null
		}
		
		private function handleDensityChanged(event:UIEvent):void {
			_model.limit = event.payload as int
			_model.folderData = _visualizer.visualize(_model.folderToVisualize, _model.limit)
			_model.selectedItem = null
		}
		
		private function handleDrilldown(event:UIEvent):void {
			try {
				var file:File = new File(event.payload as String)

				if (file.isDirectory) {
					// The currently visualizedfolder is the item that must be added to the breadcrumbs
					_model.breadCrumps.addItem(_model.folderToVisualize)
					_model.folderToVisualize = file							
					_model.folderData = _visualizer.visualize(_model.folderToVisualize, _model.limit)	
					_model.selectedItem = null
				}
			} catch (error:ArgumentError) {
				// Selected is other so do not drilldown
			}	
		}
	}
}